package com.example.demohystrixribbonconsumer;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
//@DefaultProperties(defaultFallback="xxxxx") 定义全局缺省降级方法
public class MyWebClient {
    @Autowired
    DiscoveryClient discoveryClient;

    //启用负载均衡
    @Autowired
    LoadBalancerClient loadBalancerClient;


    @Autowired
    RestTemplate restTemplate;

    //从Eureka中根据服务名称选择第一一个可用服务
    @RequestMapping(value="/ulogin1",produces = "application/json;charset=UTF-8")
    @HystrixCommand(fallbackMethod="myFallBackRibbon",
            commandProperties = {
                @HystrixProperty(name = "execution.isolation.strategy",value = "THREAD"),
                @HystrixProperty(name="execution.isilation.thread.timeoutInMilliseconds",value="8000")
            },
            threadPoolProperties = {
                @HystrixProperty(name = "coreSize",value = "2"),
                @HystrixProperty(name = "allowMaximumSizeToDivergeFromCoreSize",value="true"),
                @HystrixProperty(name = "maximumSize",value="2"),
                @HystrixProperty(name = "maxQueueSize",value="2")
         }
            )       //注解中直接设置超时时间

    public Map userlogin1() {
//        List<ServiceInstance> list = discoveryClient.getInstances ("userlogin");
//        ServiceInstance serviceInstance=list.get(0);

        //启用负载均衡
        ServiceInstance serviceInstance=loadBalancerClient.choose("USERLOGIN");

        String serviceUrl = serviceInstance.getUri().toString();
        System.out.println(serviceUrl);
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.getForObject(serviceUrl + "/login", Map.class);
    }

    @RequestMapping(value="/ulogin2",produces = "application/json;charset=UTF-8")
    @HystrixCommand(fallbackMethod="myFallBackRibbon")
    public Map userlogin2() {
        return restTemplate.getForObject("http://USERLOGIN/login", Map.class);
    }

    public Map myFallBackRibbon() {
        HashMap<String, String> map = new HashMap<>();
        map.put("error Hystrix-Ribbon RestTemplate call:", "服务器繁忙");
        return map;
    }

}

